﻿using UnityEngine;
using System.Collections.Generic;

namespace ZCUtil.Math
{
    /// <summary>
    /// 贝塞尔计算工具
    /// </summary>
    public class Bezier
    {
        #region PrivateField 贝塞尔点
        private List<Vector3> m_Vertexs;
        #endregion

        #region PublicMethod 贝塞尔点
        public List<Vector3> Vertexs
        {
            get
            {
                return m_Vertexs;
            }
        }
        #endregion

        #region PublicMethod 贝塞尔计算
        public Bezier(Vector3 p0, Vector3 p1, Vector3 p2, float vertexCount)
        {
            m_Vertexs = new List<Vector3>();

            float interval = 1 / vertexCount;

            for (int i = 0; i < vertexCount; i++)
            {
                m_Vertexs.Add(GetPoint(p0, p1, p2, i * interval));
            }
        }

        public Bezier(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float vertexCount)
        {
            m_Vertexs = new List<Vector3>();

            float interval = 1 / vertexCount;
            for (int i = 0; i < vertexCount; i++)
            {
                m_Vertexs.Add(GetPoint(p0, p1, p2, p3, i * interval));
            }
        }

        public Vector3 GetPoint(Vector3 p0, Vector3 p1, Vector3 p2, float t)
        {
            float a = 1 - t;
            Vector3 target = p0 * Mathf.Pow(a, 2) + 2 * p1 * t * a + p2 * Mathf.Pow(t, 2);
            return target;
        }

        public Vector3 GetPoint(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float t)
        {
            float a = 1 - t;
            Vector3 target = p0 * Mathf.Pow(a, 3) + 3 * p1 * t * Mathf.Pow(a, 2) + 3 * p2 * Mathf.Pow(t, 2) + p3 * Mathf.Pow(t, 3);
            return target;
        }
        #endregion
    }
}